package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    private IShopService shopService;

    @Autowired
    CacheClient cacheClient;

    private static  final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    @Override
    public Result getShopById(Long id) {
        //通过缓存空对象的方法解决缓存穿透
     //   Shop shop1 = cacheClient.getShopByThrough(CACHE_SHOP_KEY,id,Shop.class, id2 -> getById(id2),CACHE_SHOP_TTL,TimeUnit.SECONDS);
        //通过互斥锁解决缓存击穿问题
//        Shop shop = getShopByLock(id);
        //通过逻辑过期解决缓存击穿问题
        Shop shop = cacheClient.getShopByLogicalExpire(CACHE_SHOP_KEY,id, Shop.class,this::getById,20L,TimeUnit.SECONDS);
        if(null == shop){
            return Result.fail("商户不存在!");
        }
        return Result.ok(shop);
    }


    /**
     * 通过缓存空对象的方法解决缓存穿透
     * @param id
     * @return
     */
    public Shop getShopByThrough(Long id){
        //从redis中查询
        String jsonShop = redisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        if(StrUtil.isNotBlank(jsonShop)){
            Shop shop = JSONUtil.toBean(jsonShop, Shop.class);
            return shop;
        }
        //空字符串，回车符等直接返回null
        if(jsonShop != null){
            return null;
        }
        //查询数据库
        Shop shop = this.getById(id);
        if(shop == null){
            //缓存空对象
            redisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        redisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(shop),RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;

    }


    /**
     * 通过互斥锁解决缓存击穿的问题
     * @param id
     * @return
     */
    public Shop getShopByLock(Long id){
        //从redis中查询
        String jsonShop = redisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        if(StrUtil.isNotBlank(jsonShop)){
            Shop shop = JSONUtil.toBean(jsonShop, Shop.class);
            return shop;
        }
        if(jsonShop != null){
            return null;
        }
        Shop shop = null;
        try {
            //获取互斥锁
            Boolean b = tryLock(LOCK_SHOP_KEY + id);
            //获取不成功,休眠后继续重试
            if (!b) {
                Thread.sleep(50);
                getShopByLock(id);
            }
            //获取锁成功，再次检查缓存是否创建，双重监测
            String json = redisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
            if(StrUtil.isNotBlank(json)){
                Shop shop1 = JSONUtil.toBean(json, Shop.class);
                return shop1;
            }
            if(json != null){
                return null;
            }
            //查询数据库
            shop = this.getById(id);
            Thread.sleep(200);
            if(shop == null){
                //缓存空对象
                redisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
                return null;
            }
            redisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(shop),RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unLock(LOCK_SHOP_KEY + id);
        }

        return shop;

    }

    /**
     * 设置热点数据不用再仅需缓存空对象
     * @param id
     * @return
     */
    public Shop getShopByLogicalExpire(Long id){
        //从redis中查询
        String jsonShop = redisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        if(StrUtil.isBlank(jsonShop)){
            return null;
        }
        RedisData redisData = JSONUtil.toBean(jsonShop, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //没过期先返回老数据
        if (expireTime.isAfter(LocalDateTime.now())) {
            return shop;
        }

        Boolean b = tryLock(LOCK_SHOP_KEY + id);
        //获取锁失败，直接返回旧数据
        if (!b){
            return shop;
        }
        //获取锁成功再次查询缓存中是否有数据
         jsonShop = redisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        if(StrUtil.isBlank(jsonShop)){
            return null;
        }
        //开启线程重建缓存
        CACHE_REBUILD_EXECUTOR.submit(() ->{
            try {
                addHotData(id,20L);
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                unLock(LOCK_SHOP_KEY +id);
            }

        });
        return shop;

    }




    /**
     * 获取锁
     * @param key
     * @return
     */
    public Boolean tryLock(String key){
        Boolean b = redisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(b);
    }

    /**
     * 释放锁
     * @param key
     */
    public void unLock(String key){
         redisTemplate.delete(key);
    }


    @Override
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if (null == id) {
            return Result.fail("查询商户id不能为空！");
        }
        //更新数据库
        shopService.updateById(shop);

        //删除缓存
        redisTemplate.delete(CACHE_SHOP_KEY + id);

        return Result.ok("更新成功");

    }

        /**
         * 添加热点是数据
         * @param
         * @return
         */
        @Override
        public void addHotData (Long id, Long expireTime) throws InterruptedException {
            //模拟延迟
//        Thread.sleep(200);
            Shop shop = shopService.getById(id);
            //组装数据
            RedisData redisData = new RedisData();
            redisData.setData(shop);
            redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireTime));
            redisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
        }

}
